package alarm_monitor

import (
	"context"
	"device-admin/config/mysql"
	"device-admin/internal/app/grpc/protoc/robotc"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"device-admin/internal/models"
	"strconv"
	"strings"
	"time"

	"github.com/golang-module/carbon/v2"
	"google.golang.org/protobuf/proto"
)

// SaveBootSchedule 保存开机计划
func SaveBootSchedule(robotID string, msg *robotc.WildMsg) {
	rspSwitchMachineConfig := &robotc.RspSwitchMachineConfig{}
	proto.Unmarshal(msg.BodyContent, rspSwitchMachineConfig)
	timesStr := []string{}
	var newConfigs string
	oldConfigs, _ := dao.TerminalConfig{}.GetConfigs(context.Background(), dal.Q, robotID, "95", "auto_boot_shutdown")
	// 获取新的配置
	for _, config := range rspSwitchMachineConfig.GetConfigSet() {
		enable := 0
		boot := 0
		if config.BEnable {
			enable = 1
			timesStr = append(timesStr, strconv.Itoa(int(enable))+ // 使能标志
				":"+strconv.Itoa(int(boot))+ // 开机标志
				":"+strconv.Itoa(int(config.TimeHour))+ // 小时
				":"+strconv.Itoa(int(config.TimeMin)), // 分钟
			)
			newConfigs = strings.Join(timesStr, ",")
		}
	}
	// 如果配置未更新，结束设置
	if newConfigs == oldConfigs[0].Value {
		return
	}
	// 保存开关机配置
	dao.TerminalConfig{}.SaveConfigs(context.Background(), dal.Use(mysql.NewDB()), []*models.TerminalConfig{
		{
			RobotID:      robotID,
			TerminalType: "95",
			Key:          "auto_boot_shutdown",
			Value:        newConfigs,
		},
	})
	// 清除旧的开关机计划
	AlarmMonitor{}.ClearScheduleMonitor(robotID)
	// 设置新的开关机计划
	for _, config := range rspSwitchMachineConfig.GetConfigSet() {
		// 仅保存使能的开关机设置
		if config.BEnable {
			cb := carbon.CreateFromDateTime(time.Now().Year(), int(time.Now().Month()), time.Now().Day(), int(config.TimeHour), int(config.TimeMin), 0)
			if config.BIsBoot { // 添加计划开机状态监控
				// 今天的
				AlarmMonitor{}.AddMonitor(robotID, 2001, cb.Timestamp(), 2, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2002, cb.Timestamp(), 2, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2003, cb.Timestamp(), 2, true, "", "")
				// 明天的
				AlarmMonitor{}.AddMonitor(robotID, 2001, cb.Timestamp()+24*3600, 2, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2002, cb.Timestamp()+24*3600, 2, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2003, cb.Timestamp()+24*3600, 2, true, "", "")
			} else { // 添加计划关机状态监控
				// 今天的
				AlarmMonitor{}.AddMonitor(robotID, 2001, cb.Timestamp(), 0, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2002, cb.Timestamp(), 0, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2003, cb.Timestamp(), 0, true, "", "")
				// 明天的
				AlarmMonitor{}.AddMonitor(robotID, 2001, cb.Timestamp()+24*3600, 0, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2002, cb.Timestamp()+24*3600, 0, true, "", "")
				AlarmMonitor{}.AddMonitor(robotID, 2003, cb.Timestamp()+24*3600, 0, true, "", "")
			}
		}
	}
}
